<?php

namespace app\admin\service;

use app\model\User;
use app\model\UserAmountLog;
use app\model\UserRewardLog;
use app\service\WechatPay;
use think\facade\Db;
use think\Model;

class UserService extends \app\service\UserService
{

    /**
     * 提现
     * @throws \Exception
     */
    public function cashAudit(UserAmountLog $log, array $data, User $user){
        $status = $data['status']??-1;
        if ($status == 1){  // 同意

            (new \think\facade\Db)->startTrans();

            try {

                $uid = $user->id;
                $type = $log->source;
                $openid = $user->openid;
                $shopId = $user->shop_id;

                //单号
                $timestamp = time();
                $out_trade_no = $type.$openid.$shopId.$timestamp.rand(10000,99999);
                $batch_sn = md5($out_trade_no.'batch');//商户系统内部的商家批次单号
                $order_sn = md5($out_trade_no.'order');//账明细单的唯一标识

                //转账备注
                $type_data = [
                    'cash'=>'帮卖有礼提现','place'=>'自提点负责人提现',
                    'shop'=>'店长提现','busi'=>'业务员提现',
                    'parent' => '返利提现'
                ];
                $remark = $type_data[$type].'-用户ID：'.$uid.'-用户昵称：'.$user->nickname;
                if (strlen($remark) > 32) {
                    $remark = mb_substr($remark,0,32,'utf-8');
                }

                //调用微信支付
                $wechat_pay = new WechatPay($shopId);
                $result = $wechat_pay->transfer($batch_sn,$order_sn,$log->amount,$openid,$remark,$user->nickname);

                $log->status = 1;
                $log->save();

                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                throw $e;
            }


        }else{
            // 回退账户金额
            User::where('id', $user->id)->inc('amount', $log->amount)->update();
            $log->status = -1;
            $log->note = $data['note']??'';
            $log->save();

        }
    }


}
